package com.javaenzk.wfx.manager.configs;

import com.javaenzk.wfx.manager.po.User_Info;
import com.javaenzk.wfx.manager.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;

@Component
public class AccountRelam  extends AuthorizingRealm {

    @Resource
    private UserService userService;

    /**
     * 权限
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = principalCollection.getPrimaryPrincipal().toString();

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        try {
            List<String> funcList = userService.queryFuncByUseryy(username);
            simpleAuthorizationInfo.addStringPermissions(funcList);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return simpleAuthorizationInfo;
    }

    /**
     * 登录
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String username = usernamePasswordToken.getUsername();
        final char[] password1 = usernamePasswordToken.getPassword();
        String password = new String(password1);

        final User_Info userInfo = userService.login(username, password);

        SecurityUtils.getSubject().getSession().setAttribute("user",userInfo);

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username,password,"accountRealm");

        return simpleAuthenticationInfo;
    }
}
